/********* DhdtPluginPicker.swift Cordova Plugin Implementation *******/

@objc(dhdtPluginPicker) class dhdtPluginPicker : CDVPlugin, UIPickerViewDelegate, UIPickerViewDataSource {
    var CDVCommand: CDVInvokedUrlCommand?
    var per: CGFloat?

    var viewContainer: UIView?;
    var pickerViewContainer: UIView?
    var pickerView: UIPickerView?
    var buttonViewContainer: UIView?
    var button: UIButton?

    var options: NSDictionary?
    var type: String? // picker, day, date
    var defaultSelectedIndex: NSArray?
    var buttonContainerHeight: CGFloat?
    var pickerContainerHeight: CGFloat?
    var buttonStyle: NSDictionary?
    var datas: NSMutableArray?
    var rowHeight: CGFloat?
    var componentWidth: NSArray?
    var lineStyle: NSDictionary?
    var textfontStyle: NSDictionary?
    var labelText: NSArray?
    var labelStyle: NSDictionary?

    override func pluginInitialize() {
        self.per = self.webView.frame.width / 1366

//        self.options = [
//            "type": "picker",
//            "defaultSelectedIndex": [0],
//            "buttonContainerHeight": 120,
//            "pickerContainerHeight": 464,
//            "buttonStyle":["height": 88, "width": 160, "marginRight": 32,
//                           "text": "送信", "fontSize": 24],
//            "datas": ["2018(平成29)", "2018(平成29)", "2018(平成29)", "2018(平成29)", "2018(平成29)", "2018(平成29)"],
//            "rowHeight": 84.0,
//            "componentWidth": [1110],
//            "lineStyle": ["height": 4, "color":"40b9ae"],
//            "textfontStyle": ["fontSize": 48, "alignment": "center"],
//            "labelText": [],
//            "labelStyle": ["fontSize": 32, "width": 80]
//        ]

//        self.options = [
//            "type": "day",
//            "defaultSelectedIndex": [0, 0],
//            "buttonContainerHeight": 120,
//            "pickerContainerHeight": 464,
//            "buttonStyle":["height": 88, "width": 160, "marginRight": 32,
//                           "text": "送信", "fontSize": 24],
//            "datas": [],
//            "rowHeight": 84.0,
//            "componentWidth": [320, 320],
//            "lineStyle": ["height": 4, "color":"40b9ae"],
//            "textfontStyle": ["fontSize": 48, "alignment": "left"],
//            "labelText": ["月", "日"],
//            "labelStyle": ["fontSize": 32, "width": 80]
//        ]

//        self.options = [
//            "type": "date",
//            "defaultSelectedIndex": [2, 3, 1],
//            "buttonContainerHeight": 120,
//            "pickerContainerHeight": 464,
//            "buttonStyle":["height": 88, "width": 160, "marginRight": 32,
//                           "text": "送信", "fontSize": 24],
//            "datas": ["2018(平成29)", "2018(平成29)", "2018(平成29)", "2018(平成29)", "2018(平成29)", "2018(平成29)"],
//            "rowHeight": 84.0,
//            "componentWidth": [598, 320, 320],
//            "lineStyle": ["height": 4, "color":"40b9ae"],
//            "textfontStyle": ["fontSize": 48, "alignment": "left"],
//            "labelText": ["年", "月", "日"],
//            "labelStyle": ["fontSize": 32, "width": 80]
//        ]
    }

    @objc(show:) public func show(_ command: CDVInvokedUrlCommand) {
        self.CDVCommand = command
        self.options = command.arguments[0] as? NSDictionary

        self.initData()
        self.initView()

        let frame = self.viewContainer?.frame
        self.viewContainer?.frame = (frame?.offsetBy(dx: 0, dy: (frame?.size.height)!))!
        UIView.animate(withDuration: 0.3, delay: 0, options: UIViewAnimationOptions.curveEaseOut, animations: {
            self.viewContainer?.frame = frame!
        }) { (finished) in

        }
    }

    @objc(hide:) func hide(_ command: CDVInvokedUrlCommand) {
        self.dismiss()
    }

    @objc(onClickSend:) func onClickSend(sender: UIButton) {
        let result = NSMutableArray.init()

        var count = 0
        while(count < (self.pickerView?.numberOfComponents)!) {
            let rowCount = pickerView?.selectedRow(inComponent: count)
            let items = self.datas?.object(at: count) as? NSArray
            result[count] = items?.object(at: rowCount!) as Any
            count += 1
        }

        let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: result as! [Any])
        self.commandDelegate.send(pluginResult, callbackId: self.CDVCommand?.callbackId)

        self.dismiss()
    }

    func dismiss() {
        let frame = self.viewContainer?.frame.offsetBy(dx: 0, dy: (self.viewContainer?.frame.height)!)

        UIView.animate(withDuration: 0.3, delay: 0, options: UIViewAnimationOptions.curveEaseOut, animations: {
            self.viewContainer?.frame = frame!
        }) { (finished) in
            self.viewContainer?.removeFromSuperview()
        }
    }

    func initData() {
        self.type = self.options?.object(forKey: "type") as? String
        self.defaultSelectedIndex = self.options?.object(forKey: "defaultSelectedIndex") as? NSArray
        self.buttonContainerHeight = self.options?.object(forKey: "buttonContainerHeight") as? CGFloat
        self.pickerContainerHeight = self.options?.object(forKey: "pickerContainerHeight") as? CGFloat
        self.buttonStyle = self.options?.object(forKey: "buttonStyle") as? NSDictionary
        self.rowHeight = self.options?.object(forKey: "rowHeight") as? CGFloat
        self.componentWidth = self.options?.object(forKey: "componentWidth") as? NSArray
        self.lineStyle = self.options?.object(forKey: "lineStyle") as? NSDictionary
        self.textfontStyle = self.options?.object(forKey: "textfontStyle") as? NSDictionary
        self.labelText = self.options?.object(forKey: "labelText") as? NSArray
        self.labelStyle = self.options?.object(forKey: "labelStyle") as? NSDictionary

        self.datas = NSMutableArray.init()
        if "date" == self.type {
            self.datas?.add(self.options?.object(forKey: "datas") as Any)
            self.datas?.add(self.getNumberList(max: 12))
            self.datas?.add(self.getNumberList(max: 31))
        } else if "day" == self.type {
            self.datas?.add(self.getNumberList(max: 12))
            self.datas?.add(self.getNumberList(max: 31))
        } else {
            self.datas?.add(self.options?.object(forKey: "datas") as Any)
        }
    }

    func initView() {
        var pickerWidth: CGFloat = 0
        for w in self.componentWidth! {
            pickerWidth += w as! CGFloat
        }
        pickerWidth *= self.per!

        let width = self.webView.frame.width
        let height = self.webView.frame.height

        let y = height - (self.buttonContainerHeight! + self.pickerContainerHeight!) * self.per!
        self.viewContainer = UIView.init(frame: CGRect(x: 0, y: y, width: width, height: height))
        self.viewContainer?.backgroundColor = UIColor.white
        self.webView.addSubview(self.viewContainer!)

        let bCHeight = self.buttonContainerHeight! * self.per!
        self.buttonViewContainer = UIView.init(frame: CGRect(x: 0, y: 0, width: width, height: bCHeight))
        self.viewContainer?.addSubview(self.buttonViewContainer!)

        var bWidth: CGFloat = self.buttonStyle?.object(forKey: "width") as! CGFloat
        bWidth = bWidth * self.per!
        var bHeigth: CGFloat = self.buttonStyle?.object(forKey: "height") as! CGFloat
        bHeigth = bHeigth * self.per!
        var bMarginRight: CGFloat = self.buttonStyle?.object(forKey: "marginRight") as! CGFloat
        bMarginRight = bMarginRight * self.per!
        let bX = width - bWidth - bMarginRight
        let bY = (bCHeight - bHeigth) / 2
        self.button = UIButton.init(type: UIButtonType.custom)
        self.button?.frame = CGRect.init(x: bX, y: bY, width: bWidth, height: bHeigth)
        self.button?.setTitle(self.buttonStyle?.object(forKey: "text") as? String, for: UIControlState.normal)
        self.button?.backgroundColor = UIColor.clear
        let fontSize = self.buttonStyle?.object(forKey: "fontSize") as? CGFloat
        self.button?.titleLabel?.font = UIFont.boldSystemFont(ofSize: fontSize! * self.per!)
        let path = Bundle.main.path(forResource: "UP_Bank_Icon@2x", ofType: "png")
        let image = UIImage(contentsOfFile: path!)
        self.button?.setImage(image, for: UIControlState.normal)
        self.button?.imageEdgeInsets = UIEdgeInsets.init(top: 0, left: -20, bottom: 0, right: 0)
        self.button?.layer.cornerRadius = bHeigth / 2
        self.button?.addTarget(self, action: #selector(self.onClickSend(sender:)), for: UIControlEvents.touchUpInside)

        let bgView = UIView.init(frame: (self.button?.frame)!)
        let gradientLayer = CAGradientLayer()
        gradientLayer.frame = (self.button?.bounds)!
        gradientLayer.colors = [
            self.colorWithHexString(hex: "3ad88f").cgColor,
            self.colorWithHexString(hex: "40b9ae").cgColor
        ]
        gradientLayer.startPoint = CGPoint.init(x: 0, y: 0.5)
        gradientLayer.endPoint = CGPoint.init(x: 1, y: 0.5)
        gradientLayer.cornerRadius = bHeigth / 2
        bgView.layer.addSublayer(gradientLayer)
        self.buttonViewContainer?.addSubview(bgView)
        self.buttonViewContainer?.addSubview(self.button!)

        let lineView = UIView.init(frame: CGRect(x: 0, y: 0, width: width, height: 2))
        lineView.backgroundColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0.1)
        self.viewContainer?.addSubview(lineView)

        let cWidth = self.viewContainer?.frame.width
        let cHeight = self.pickerContainerHeight! * self.per!
        self.pickerViewContainer = UIView.init(frame: CGRect(x: (cWidth! - pickerWidth)/2, y: bCHeight, width: pickerWidth, height: cHeight))
        self.viewContainer?.addSubview(self.pickerViewContainer!)

        let pHeight = self.pickerViewContainer?.frame.height
        self.pickerView = UIPickerView.init(frame: CGRect(x: 0, y: 0, width: pickerWidth, height: pHeight!))
        self.pickerView?.delegate = self
        self.pickerView?.dataSource = self
        self.pickerViewContainer?.addSubview(self.pickerView!);

        for (i, value) in (self.defaultSelectedIndex?.enumerated())! {
            self.pickerView?.selectRow(value as! Int, inComponent: i, animated: false)
        }
    }

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        if "date" == self.type {
            return 3
        } else if "day" == self.type {
            return 2
        }
        return (self.datas?.count)!
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        let item = self.datas?[component] as? NSArray
        return (item?.count)!;
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        let item = self.datas?[component] as? NSArray
        return item![row] as? String;
    }

    func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
        return (self.rowHeight! * self.per!);
    }

    func pickerView(_ pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat {
        let w = self.componentWidth![component] as? CGFloat
        return (w! * self.per!)
    }

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        if "date" == self.type {
            if component == 0 {
                let itemY = self.datas?[0] as? NSArray
                let year = itemY?[row] as? String
                let itemM = self.datas?[1] as? NSArray
                let rowCount = pickerView.selectedRow(inComponent: 1)
                let month = itemM?[rowCount] as? String
                let array = self.getDaysOfMonth(year: year!, month: month!)
                self.datas?.removeObject(at: 2)
                self.datas?.add(array)
                self.pickerView?.reloadComponent(2)
            } else if component == 1 {
                let itemY = self.datas?[0] as? NSArray
                let rowCount = pickerView.selectedRow(inComponent: 0)
                let year = itemY?[rowCount] as? String
                let itemM = self.datas?[1] as? NSArray
                let month = itemM?[row] as? String
                let array = self.getDaysOfMonth(year: year!, month: month!)
                self.datas?.removeObject(at: 2)
                self.datas?.add(array)
                self.pickerView?.reloadComponent(2)
            }
        } else if "day" == self.type {
            if component == 0 {
                let item = self.datas?[component] as? NSArray
                let month = item?[row] as? String
                let array = self.getDaysOfMonth(year: "", month: month!)
                self.datas?.removeObject(at: 1)
                self.datas?.add(array)
                self.pickerView?.reloadComponent(1)
            }
        }
    }

    func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
        for lineView in pickerView.subviews {
            if (lineView.frame.size.height < 1) {
                let height: CGFloat = self.lineStyle?.object(forKey: "height") as! CGFloat
                lineView.frame.size.height = height * self.per!
                lineView.backgroundColor = self.colorWithHexString(hex: self.lineStyle?.object(forKey: "color") as! String)
            }
        }

        if 0 < (self.labelText?.count)! {
            self.setLabelView(pickerView, component)
        }
        return getTextView(row, component)
    }

    func setLabelView(_ pickerView: UIPickerView, _ component: Int) {
        let width = self.getLabelX(component)
        let labelWidth: CGFloat = self.labelStyle?.object(forKey: "width") as! CGFloat

        let labelView = UILabel.init()
        labelView.frame = CGRect.init(x: (width - labelWidth * self.per!), y: 0, width: labelWidth * self.per!, height: pickerView.frame.height)
        labelView.text = self.labelText?[component] as? String
        labelView.textAlignment = NSTextAlignment.center
        labelView.backgroundColor = UIColor.white
        let fontSize = self.labelStyle?.object(forKey: "fontSize") as? CGFloat
        labelView.font = UIFont.boldSystemFont(ofSize: fontSize! * self.per!)
        pickerView.addSubview(labelView)
    }

    func getTextView(_ row: Int, _ component: Int) -> UILabel {
        let item = self.datas?[component] as? NSArray
        let text = item![row] as? String;

        let textView = UILabel.init()
        textView.text = text!
        let fontSize = self.textfontStyle?.object(forKey: "fontSize") as? CGFloat
        textView.font = UIFont.boldSystemFont(ofSize: fontSize! * self.per!)

        textView.textAlignment = NSTextAlignment.center
        if "left" == self.textfontStyle?.object(forKey: "alignment") as! String {
            textView.text = "  " + text!
            textView.textAlignment = NSTextAlignment.left
        }

        return textView
    }

    func getLabelX(_ component: Int) -> CGFloat {
        var width: CGFloat = 0
        for(i, value) in (self.componentWidth?.enumerated())! {
            width += value as! CGFloat

            if i == component {
                break
            }
        }

        return width * self.per!
    }

    func getNumberList(max: Int) -> NSArray {
        let array = NSMutableArray.init()
        var count = 1
        while(count <= max) {
            array.add(String(count))
            count += 1
        }

        return array
    }

    func getDaysOfMonth(year: String, month: String) -> NSArray {
        let smallMonth = ["4", "6", "9", "11"]
        if "2" == month {
            return self.isLeapYear(year: year) ? self.getNumberList(max: 29) : self.getNumberList(max: 28)
        } else if smallMonth.contains(month) {
            return self.getNumberList(max: 30)
        }
        return self.getNumberList(max: 31)
    }

    func isLeapYear(year: String) -> Bool {
        if (year.count < 4) {
            return false;
        }
        let y = Int(year.substring(to: year.index(year.startIndex, offsetBy: 4)))
        return (y!%4 == 0 && y!%100 != 0 || y!%400 == 0)
    }

    func colorWithHexString (hex: String) -> UIColor {
        let cString: String = hex.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines).uppercased()

        let rString = (cString as NSString).substring(to: 2)
        let gString = ((cString as NSString).substring(from: 2) as NSString).substring(to: 2)
        let bString = ((cString as NSString).substring(from: 4) as NSString).substring(to: 2)

        var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0;
        Scanner(string: rString).scanHexInt32(&r)
        Scanner(string: gString).scanHexInt32(&g)
        Scanner(string: bString).scanHexInt32(&b)

        return UIColor(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: CGFloat(1))
    }
}
